﻿define("vm.aupair.favorite",
	["jquery", "ajax-util", "common", "dataservice", "model.aupair", "presenter"],
	function ($, util, common, ds, aupairObj, presenter) {
		var bindFavoriteAupairs = ko.observableArray([]),
			bindCCAPFavoriteAupairs = ko.observableArray([]),
			selectedAupairDataToRemove = [],
			selectedAupairDataToHold = [],
			appcode = ko.observable(),
			staffDuties = ko.observableArray(),

			SetAppCode = function (code) {
				appcode(code);
			},

			MakeFavorite = function (data, favButton) {
				if (appcode() == 'SAS') { // SAS
					var apID = data;
					if (apID.EncAupairID != undefined)
						apID = data.EncAupairID;
					greyedBackground.show();
					ds.aupair.MakeFavorite({
						success: function (pResult) {
							greyedBackground.hide();
							if (pResult == "Success") {
								if (data.IsFavoriteAupair != undefined)
									data.IsFavoriteAupair = true;
								if (viewModels != null && viewModels.vmapv != null)
									viewModels.vmapv.CanFavorite(0);
								favButton[0].className = 'thb-action btn btn-primary favorite';
								$(favButton).siblings('.favorites-comment-box').show();

								if (viewModels.vmap != null) {
									favoriteAupairs = [];
									favoriteAupairs.push(new aupairObj(data));
									$.each(bindFavoriteAupairs(), function (key, val) {
										favoriteAupairs.push(new aupairObj(val));
									})
									bindFavoriteAupairs(favoriteAupairs);
									favsSlide();
								}
							}
							else {
								greyedBackground.hide();
								common.ErrorNotify(pResult);
							}
						},
						error: function () {
							greyedBackground.hide();
							common.ErrorNotify(msgs["fav_ap_added_error"]);
						}
					},
					{
						AuPairId: apID,
						Comments: ''
					});
				}
				else { //SAV
					var apID = data;
					if (apID.EncAupairID != undefined)
						apID = data.EncAupairID;
					var staffcomments = $(favButton).parent().siblings('.favoriteComment').val();
					if ($.trim(staffcomments) == '' || staffcomments == undefined || staffcomments == null) {
						$(favButton).parent().siblings('.favoriteComment').after($('<span class="error">Please enter your notes.</span>'));
						return;
					}
					greyedBackground.show();
					ds.aupair.MakeFavorite({
						success: function (pResult) {
							greyedBackground.hide();
							if (pResult == "Success") {
								if (data.IsFavoriteAupair != undefined)
									data.IsFavoriteAupair = true;
								if (viewModels != null && viewModels.vmapv != null)
									viewModels.vmapv.CanFavorite(0);
								favButton[0].className = 'thb-action btn btn-primary favorite';
								$.magnificPopup.close();
								greyedBackground.hide();
								$(favButton).parent().siblings('.favoriteComment').val('');
								$(favButton).parent().parent().hide()
							}
							else {
								greyedBackground.hide();
								common.ErrorNotify(pResult);
							}
						},
						error: function () {
							greyedBackground.hide();
							common.ErrorNotify(msgs["fav_ap_added_error"]);
						}
					},
					{
						AuPairId: apID,
						Comments: staffcomments
					});
				}
			},

		RemoveFromFavorite = function (data, favButton) {
			if (appcode() == 'SAS') { //SAS
				var EncAupairID;
				if (data.EncAupairID != undefined && data.EncAupairID != null && data.EncAupairID != '') {
					EncAupairID = data.EncAupairID;
				}
				else {
					EncAupairID = common.GetQueryStringValue('apKey');
				}

				$.magnificPopup.close();
				greyedBackground.show();
				ds.aupair.RemoveFavAP({
					success: function (pResult) {
						greyedBackground.hide();
						if (pResult == "Success") {
							data.IsFavoriteAupair = false;

							if (viewModels.vmapv != undefined) {
								viewModels.vmapv.CanFavorite(1);
							}

							if (favButton != undefined && favButton[0] != undefined) {
								favButton[0].className = 'thb-action btn btn-primary not-favorite';
							}

							if (viewModels.vmap != null) {
								$.each(bindFavoriteAupairs(), function (key, val) {
									if (val.EncAupairID == EncAupairID) {
										bindFavoriteAupairs.remove(val);
										return false;
									}
								})
							}

							common.SuccessNotify(msgs["fav_ap_remove_success"]);
						}
						else {
							common.ErrorNotify(pResult);
						}
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["fav_ap_remove_error"]);
					}
				},
				{
					pAupairId: EncAupairID
				});
			}
			else { //SAV
				var EncAupairID = common.GetQueryStringValue('A')
				$.magnificPopup.close();
				greyedBackground.show();
				ds.aupair.RemoveFavAP({
					success: function (pResult) {
						greyedBackground.hide();
						if (pResult == "Success") {
							data.IsFavoriteAupair = false;
							if (viewModels.vmapv != undefined) {
								viewModels.vmapv.CanFavorite(1);
							}

							if (viewModels.vmap != null) {
								$.each(bindFavoriteAupairs(), function (key, val) {
									if (val.EncAupairID == EncAupairID) {
										bindFavoriteAupairs.remove(val);
										return false;
									}
								})
							}

							common.SuccessNotify(msgs["fav_ap_remove_success"]);
						}
						else {
							common.ErrorNotify(pResult);
						}
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["fav_ap_remove_error"]);
					}
				},
				{
					pAupairId: EncAupairID
				});
			}
		},

		RemoveAPfromFav = function (fromAPViewer) {
			$.magnificPopup.close();
			greyedBackground.show();
			ds.aupair.RemoveFavAP({
				success: function (pResult) {
					greyedBackground.hide();
					if (pResult == "Success") {
						if (fromAPViewer == true) {
							$('.remove-from-fav').hide();
							$('.add-as-fav').show();
						}
						else {
							if (selectedAupairDataToRemove.FavoriteAddedBy == 'HF'
								|| selectedAupairDataToRemove.FavoriteAddedBy == '') {
								bindFavoriteAupairs.remove(selectedAupairDataToRemove);
							}
							else {
								bindCCAPFavoriteAupairs.remove(selectedAupairDataToRemove);
							}
						}
						common.SuccessNotify(msgs["fav_ap_remove_success"]);
					}
					else {
						common.ErrorNotify(pResult);
					}
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["fav_ap_remove_error"]);
				}
			},
			{
				pAupairId: common.GetAupairID(selectedAupairDataToRemove)
			});
		},

		SaveFavoriteComment = function (pAupairID, pComment) {
			if (appcode() == 'SAS') { //SAS
				greyedBackground.show();
				ds.aupair.SaveFavoriteComment({
					success: function (pResult) {
						greyedBackground.hide();
						if (pResult == "Successful") {
							common.SuccessNotify(msgs["fav_ap_comment_success"]);
							$(".favorites-comment-box").hide();
							$('.favoriteComment').val('');
						}
						else {
							common.ErrorNotify(pResult);
							$.magnificPopup.close();
							$(".favorites-comment-box").hide();
							$('.favoriteComment').val('');
						}
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["fav_ap_comment_error"]);
						$(".favorites-comment-box").hide();
						$('.favoriteComment').val('');
					}
				},
				{
					pAupairID: pAupairID,
					pComment: pComment
				});
			}
			else { //SAV
				ds.aupair.SaveFavoriteComment({
					success: function (pResult) {
						if (pResult == "Successful") {
							common.SuccessNotify(msgs["fav_ap_comment_success"]);
							$.magnificPopup.close();
						}
						else {
							common.ErrorNotify(pResult);
							$.magnificPopup.close();
						}
					},
					error: function () {
						common.ErrorNotify(msgs["fav_ap_comment_error"]);
					}
				},
				{
					pAupairID: pAupairID,
					pComment: pComment
				});
			}
		},

		GetFavoriteAupairs = function () {
			if (appcode() == 'SAS') { //SAS
				return $.Deferred(function (def) {
					ds.aupair.GetFavoriteAupairs({
						success: function (pResult) {
							favoriteAupairs = [];
							ccapFavoriteAupairs = [];
							if (pResult !== undefined) {
								$.each(pResult, function (key, val) {
									if (val.CanReserveAupair != 'matched-with-you') {
										if (val.FavoriteAddedBy == 'HF' || val.FavoriteAddedBy == '') {
											favoriteAupairs.push(new aupairObj(val));
										}
										else {
											ccapFavoriteAupairs.push(new aupairObj(val));
										}
									}
								})
								bindFavoriteAupairs(favoriteAupairs);
								bindCCAPFavoriteAupairs(ccapFavoriteAupairs);
							};
							def.resolve();
						},
						error: function (response) {
							common.ErrorNotify(msgs["fav_load_error"]);
							def.reject();
						}
					});
				}).promise();			
			}
			else {
				greyedBackground.show();
				ds.aupair.GetFavoriteAupairs({
					success: function (pResult) {
						greyedBackground.hide();
						favoriteAupairs = [];
						ccapFavoriteAupairs = [];
						if (pResult !== undefined) {
							$.each(pResult, function (key, val) {

								if (val.FavoriteAddedBy == 'HF' || val.FavoriteAddedBy == '') {
									favoriteAupairs.push(new aupairObj(val));
								}
								else {
									ccapFavoriteAupairs.push(new aupairObj(val));
								}
								
							})
							bindFavoriteAupairs(favoriteAupairs);
							bindCCAPFavoriteAupairs(ccapFavoriteAupairs);
							viewModels.vmapr.DisplayMaxReserveAlert();
						};

						descriptionOverflow();
						AnimatePage();
					},
					error: function (response) {
						greyedBackground.hide();
						common.ErrorNotify(msgs["fav_load_error"]);
					}
				}
			   );			
			}
		},

		AnimatePage = function () {
			var element;
			element = $('.subPageProfiles');
			presenter.AnimateElement(element);
		},

		ViewAupair = function () {
			if (appcode() == 'SAS') { //SAS
				common.ViewAupair(viewModels, this);
			}
			else { //SAV
				common.ViewAupair(this);
			}
		},

		ReserveAupair = function () {
			if (appcode() == 'SAS') { //SAS
				greyedBackground.show();
				var apID = common.GetAupairID(this);
				var pmname = '';
				$.each(bindFavoriteAupairs(), function (key, val) {
					if (val.EncAupairID == apID) {
						pmname = val.PMName;
					}
				});
				$.each(bindCCAPFavoriteAupairs(), function (key, val) {
					if (val.EncAupairID == apID) {
						pmname = val.PMName;
					}
				});
				ds.reserveAupair.ReserveAupair({
					success: function (pResult) {
						greyedBackground.hide();
						if (pResult == "Successful") {
							common.SuccessNotify(msgs["reserve_ap_success"]);
							if (viewModels != null && viewModels.vmapfh != null) {
								viewModels.vmapfh.Init();
							}
							else {
								window.location.href = viewModels.reservedPageURL;
							}
						}
						else {
							if (pResult == 'restrict-48-hour-hold') {
								if (viewModels != null && viewModels.vmapr != null) {
									var primaryMatches = viewModels.vmapr.PrimaryMatches();
									if (viewModels.vmapfh != null) {
										viewModels.vmapfh.SelectedAupairForExtendedHold(apID);
									}

									if (primaryMatches.length > 0) {
										if ((primaryMatches[0].Status != "PM" && primaryMatches[0].Status != "PME") ||
											primaryMatches[0].Is48HourHoldRestrictionApplies == true) {
											$('.make-pm-48hr-restrict').find('.releaseExtnHold').show();
										}
									}

									makePMFor48HrRestrict();
								}
							}
							else if (pResult == 'BlockedReserve') {
								$('#blockreservefavholdspan').text(msgs["blockrestrictmessage"].replace("<<PlacementManager>>", pmname));
								$(this).scrollTop(0);
							}
							else {
								common.ErrorNotify(pResult);
							}
						}
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["reserve_ap_error"]);
					}
				},
				{
					AuPairId: apID
				});
			}
			else { //SAV
				greyedBackground.show();
				ds.reserveAupair.ReserveAupair({
					success: function (pResult) {
						greyedBackground.hide();
						if (pResult == "Successful") {
							GetFavoriteAupairs();
							common.SuccessNotify(msgs["reserve_ap_success"]);
						}
						else {
							common.ErrorNotify(pResult);
						}
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["reserve_ap_error"]);
					}
				},
				{
					pAupairID: common.GetAupairID(this)
				});
			}
		},

		IsExtensionAP = function (pApStatus) {
			return common.IsExtensionAP(pApStatus);
		},

		RemoveFavAP = function (data, obj) {
			selectedAupairDataToRemove = data;
			common.ShowMessage('', 'remove-from-fav');
		},

		makePMFor48HrRestrict = function () {
			$.magnificPopup.open({
				type: 'inline',
				closeOnContentClick: false,
				closeOnBgClick: true,
				showCloseBtn: false,
				enableEscapeKey: false,
				items: {
					src: '.make-pm-48hr-restrict'
				}
			});
		},

		AddAsFavAP = function (data, obj) {
			$(obj.target).siblings('.favorites-comment-box').show();
		},

		init = function () {
			if (appcode() != 'SAS') {
				GetFavoriteAupairs();
				viewModels.vmapv.CanReserveAndFavoriteAupair();
			}
		},
		
		ValidateReserveByLCC = function () {
			$('#err_lcc_reservesite').hide();
			$('#err_lcc_reservereason').hide();

			if ($('#ddlLCC_ReserveSite').val() == '') {
				$('#err_lcc_reservesite').show();
			}
			if ($.trim($('#txtLCC_ReserveReason').val()) == '') {
				$('#err_lcc_reservereason').show();
			}
			else if ($.trim($('#txtLCC_ReserveReason').val()).length <= 5) {
				$('#err_lcc_reservereason').show();
			}

			if ($('#ddlLCC_ReserveSite').val() == '' || $('#txtLCC_ReserveReason').val() == '' || $.trim($('#txtLCC_ReserveReason').val()).length <= 5) {
				return false;
			}

			return true;
		},		

		ReserveAupairByLCC = function () {
			if (ValidateReserveByLCC()) {
				greyedBackground.show();
				ds.reserveAupair.ReserveAupairByLCC({
					success: function (pResult) {
						greyedBackground.hide();
						if (pResult == "Successful") {
							GetStaffDuties();
							$.magnificPopup.close();
							common.SuccessNotify(msgs["reserve_ap_success"]);
						}
						else if (pResult != "") {
							common.ErrorNotify(pResult);
						}
						else {
							common.ErrorNotify(msgs["reserve_ap_error"]);
						}
					},
					error: function () {
						greyedBackground.hide();
						common.ErrorNotify(msgs["reserve_ap_error"]);
					}
				},
				{
					AuPairId: common.GetAupairID(),
					Site: $('#ddlLCC_ReserveSite').val(),
					Comments: $('#txtLCC_ReserveReason').val()
				});

			}

		},

		ReserveAupairByStaff = function () {
			//Remove the previous validation error messages
			$('#divStaffHoldAupair').parents().find('.line-break').remove()
			$('#divStaffHoldAupair').parents().find('span[class="error"]').remove();

			//This is a fix for IE8. In IE8 if the textbox is empty, .val() takes placeholder as the value
			var plchold = $('#txtStaff_HoldReason').attr("placeholder");

			if ($.trim($('#txtStaff_HoldReason').val()) == '' || (plchold != undefined && plchold != null && plchold != '' && plchold == $.trim($('#txtStaff_HoldReason').val()))) {
				$('#txtStaff_HoldReason').after($('<span class="error">Please enter matching reason.</span>'));
				return;
			}

			greyedBackground.show();
			ds.reserveAupair.ReserveAupairByStaff({
				success: function (pResult) {
					greyedBackground.hide();
					if (pResult == "Successful") {
						$('#txtStaff_HoldReason').val('');
						$.magnificPopup.close();
						init(false);
						GetStaffDuties(common.GetAupairID(selectedAupairDataToHold));
						common.SuccessNotify(msgs["reserve_ap_success"]);
					}
					else if (pResult == "BlockedReserve") {
						init(false);
					}
					else if (pResult == "restrict-48-hour-hold") {
						init(false);
						common.ErrorNotify(msgs["restrict-48-hour-hold"]);
					}
					else if (pResult != "") {
						common.ErrorNotify(pResult);
					}
					else {
						common.ErrorNotify(msgs["reserve_ap_error"]);
					}
				},
				error: function () {
					greyedBackground.hide();
					common.ErrorNotify(msgs["reserve_ap_error"]);
				}
			},
			{
				AuPairId: common.GetAupairID(selectedAupairDataToHold),
				Comments: $('#txtStaff_HoldReason').val()
			});
		},
		
		InitializeReserveAPByLcc = function () {
			$('#err_lcc_reservesite').hide();
			$('#err_lcc_reservereason').hide();
			$.magnificPopup.open({
				type: 'inline',
				closeOnContentClick: false,
				closeOnBgClick: true,
				showCloseBtn: false,
				enableEscapeKey: false,
				items: {
					src: '#divLCCReserveAupair'
				}
			});
		},

		InitializeReserveAPByStaff = function () {
		selectedAupairDataToHold = this;
			$.magnificPopup.open({
				type: 'inline',
				closeOnContentClick: false,
				closeOnBgClick: true,
				showCloseBtn: false,
				enableEscapeKey: false,
				items: {
					src: '#divStaffHoldAupair'
				}
			});
		},

		GetStaffDuties = function (data) {
			var apid = common.GetAupairID(this);
			if (apid == null || apid == undefined || apid == '') {
				apid = data;
			}
			ds.aupair.GetStaffDuties({
				success: function (pResult) {
					staffDuties(pResult);
				},
				error: function () {
					common.ErrorNotify(msgs["viewer_load_options_error"])
				}
			}, apid);
		};		

		return {
			Init: init,
			MakeFavorite: MakeFavorite,
			RemoveAPfromFav: RemoveAPfromFav,
			BindFavoriteAupairs: bindFavoriteAupairs,
			ReserveAupair: ReserveAupair,
			FavoriteAupairs: GetFavoriteAupairs,
			ViewAupair: ViewAupair,
			GetReserveButtonStyle: common.GetReserveButtonStyle,
			GetReserveButtonTooltip: common.GetReserveButtonTooltip,
			IsExtensionAP: IsExtensionAP,
			WatchVideo: common.WatchVideo,
			RemoveFavAP: RemoveFavAP,
			SaveFavoriteComment: SaveFavoriteComment,
			RemoveFromFavorite: RemoveFromFavorite,
			AddAsFavAP: AddAsFavAP,
			ReserveAupairByLCC: ReserveAupairByLCC,
			ReserveAupairByStaff: ReserveAupairByStaff,
			BindCCAPFavoriteAupairs: bindCCAPFavoriteAupairs,
			GetReserveButtonText: common.GetReserveButtonText,
			Appcode: appcode,
			SetAppCode: SetAppCode,
			InitializeReserveAPByLcc: InitializeReserveAPByLcc,
			InitializeReserveAPByStaff: InitializeReserveAPByStaff,
			StaffDuties: staffDuties,
			GetStaffDuties: GetStaffDuties
		}
	});